<?php

namespace App\Transformers;

use App\Transformers\Contracts\ResponseInterface;
use App\Transformers\Exceptions\CannotTransformResponseException;
use Symfony\Component\HttpFoundation\Response as BaseResponse;
use Illuminate\Http\Response;

class ResponseService extends Response implements ResponseInterface
{
    /**
     * @param $response
     * @return ResponseService
     * @throws CannotTransformResponseException
     */
    public static function createFromBase($response): ResponseService
    {
        if ($response instanceof static)
            return $response;

        if ($response instanceof BaseResponse)
            $response = (new static)->duplicate($response->getContent(), $response->getStatusCode(), $response->headers);

        else
            throw new CannotTransformResponseException(typeOf($response));

        return $response;
    }

    public function send()
    {
        $this->transform();

        return parent::send();
    }

    /**
     * @param $content
     * @param $statusCode
     * @param $headers
     * @return $this
     */
    public function duplicate($content, $statusCode, $headers)
    {
        $this->setContent($content);

        $this->setStatusCode($statusCode);

        $this->headers = $headers;

        return $this;
    }

    /**
     * @return Response
     */
    public function transform(): Response
    {
        $this->transformBody();

        return $this;
    }

    public function transformBody()
    {
        if (is_string($this->original) && is_array($original = json_decode($this->original, true)))
            $this->transformJson($original);
    }

    protected function transformJson(array $original)
    {
        $content = $this->isSuccessful() ? [
            'data' => $original,
        ] : $original;

        $this->setContent($content);
    }
}